//
//  RCRefreshView.swift
//  RC-微博0305
//
//  Created by 任淳 on 16/3/15.
//  Copyright © 2016年 ReverChun. All rights reserved.
//

import UIKit

enum refreshStatuse: Int {
    
    case Normal = 0  //默认状态
    case Pulling = 1  //松手刷新状态
    case Refreshing = 2  //正在刷新
    
}


class RCRefreshView: UIControl {

    //状态的属性
    var statuse:refreshStatuse = .Normal{
        didSet {
            switch statuse {
            case .Normal:
                print("下拉刷新")
                arrowIcon.hidden = false
                indicationView.stopAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //让视图旋转后回到原来的角度位置
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    if oldValue == .Refreshing {
                        //刷新完就不让菊花转了
                        //还要让刷新视图上去 把contentInset回复到原始状态
                        var inSet = self.scrollView!.contentInset
                        inSet.top -= 60
                        self.scrollView?.contentInset = inSet
                        
                    }
                    
                })
                
                
            case .Pulling:
                print("松手刷新")
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
                
            case .Refreshing:
                print("正在刷新")
                arrowIcon.hidden = true
                indicationView.startAnimating()
                //发送值改变的消息 执行值改变时执行的方法
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.3, animations: { () -> Void in
                    
                    var inSet = self.scrollView!.contentInset
                    inSet.top += 60
                    self.scrollView?.contentInset = inSet
                    
                })
                
            }
        }
    }
    

    
    
    //刷新控件给定默认值 直接在构造方法内部指定大小
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -60, width: UIScreen.mainScreen().bounds.width, height: 60)
        super.init(frame: rect)
        //设置背景颜色
//        self.backgroundColor = UIColor.purpleColor()
        
        
        
        //设置界面
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //KVO观察方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let offSetY = scrollView?.contentOffset.y
        //如果在拖动中
        if scrollView!.dragging {
            //若果偏移量小于124 默认就是64 加上刷新视图的height
            //待刷新状态下 并且偏移量小于124 在回到默认状态
            if statuse == .Pulling && offSetY > -124 {
                //下拉刷新 没达到临界值124 默认状态下拉刷新
                statuse = .Normal
                
             //之前是默认状态 并且达到临界值 再松手刷新 是松手刷新状态就不再刷新
            }else if statuse == .Normal && offSetY < -124 {
                //松手刷新 等待刷新状态
                statuse = .Pulling
            }
            
        }else {
           //没有拖拽父视图视图 并且等待刷新时 是刷新状态
            if statuse == .Pulling {
                statuse = .Refreshing
                
            }
        }
        
    }
    
    //正在刷新状态之后 要把状态回复要默认 也就是加载完网络数据之后
    func endRefreshing() {
        //延迟执行
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(USEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statuse = .Normal
        }
        
    }
    
    //要实时观察 父视图的contentOffset属性 的实时变化 来判断下拉刷新视图的状态
    //自己将要被添加到父视图的时候执行
    override func willMoveToSuperview(newSuperview: UIView?) {
        //掉一下父类
        super.willMoveToSuperview(newSuperview)
        //如果自己的父视图是UIScrollView 或者继承自UIScrollView 就用scrollView 接收一下
        if let fatherView = newSuperview as? UIScrollView {
            
            scrollView = fatherView
            //实时观察父视图contentOffset的变化
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
        
    }
    
    //懒加载一个UIScrollView
    var scrollView:UIScrollView?
    
    private func setupUI() {
       
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
        
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            
        }
        
    }

    
    //MARK: 懒加载子视图
    private lazy var tipLabel: UILabel = UIFactory.labelWith("下拉刷新", textColor: UIColor.darkGrayColor(), fontSize: 14)
    
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))

    
    //移除监听
    deinit {
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
